const express = require("express");
const db = require("./lib/DBHelper");
const moment = require("moment");
const cors = require("cors");


//初始express
let server = express();

//把我们写的静态页面,当做服务器的静态资源
//别人访问,node服务器,就能访问你的页面
server.use(express.static("./../src/"));

//配合中间件
server.use(cors());//跨域
server.use(express.urlencoded({ extended: false }));
server.use(express.json());//接受json



//post,注册接口
server.post("/reg", async (request, resposne, next) => {

    try {
        let reg_sql = "INSERT INTO `userinfo` (`u_nikename`,`u_name`,`u_pwd`,`u_sex`,`u_createtime`)";
        reg_sql += "VALUES(?,?,?,?,?);";
        let reg_params = [
            request.body.nikename,
            request.body.name,
            request.body.pwd,
            request.body.sex,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ]

        let result = await db.exec(reg_sql, reg_params);
        let oMessages = {
            msg: "注册失败!",
            code: -200
        }
        if (result.affectedRows >= 1) {
            oMessages["msg"] = "注册成功!";
            oMessages["code"] = "200";
        }

        resposne.json(oMessages)
    } catch (error) {
        let oMessages = {
            msg: "注册失败!",
            code: -200,
            error
        }
        resposne.json(oMessages);
    }

})

//get 用query
//post 用 body

server.get("/validataName", async (request, resposne, next) => {
    let name = request.query.name;// get请求用query获取前端传递过来的参数
    let sql = "SELECT `u_name` FROM `userinfo` WHERE `u_status`=1 AND `u_name`=?;";
    let prams = [name];
    let result = await db.exec(sql, prams);

    var msg = result.length >= 1 ? "false" : "true";
    resposne.send(msg);
})

//登录
server.post("/login", async (request, resposne, next) => {

    try {

        let login_sql = "SELECT `u_id`,`u_nikename`,`u_name`,`u_sex`,`u_createtime`,`u_avatar` FROM `userinfo` ";
        login_sql += " WHERE`u_status` = 1 AND u_name =? AND`u_pwd` =? ;";
        let login_params = [
            request.body.name,
            request.body.pwd
        ]
        let result = await db.exec(login_sql, login_params)
        let oMessage = {
            msg: "登录失败",
            code: -200
        }
        if (result.length >= 1) {
            oMessage["msg"] = "登录成功!";
            oMessage["code"] = 200;
            oMessage["data"] = result[0]
        }
        resposne.json(oMessage)

    } catch (error) {
        let oMessage = {
            msg: "登录失败",
            code: -200,
            error
        }
        resposne.json(oMessage)

    }

})

//设置监听
server.listen(8080, () => {
    console.log("中酒网apis启动完毕!");
})

// nodemon 自动重启服务
// cnpm i nodemon -g
// nodemon app.js